import {
  Controller,
  Get,
  Query,
  UseInterceptors,
  Version,
  Inject,
} from '@nestjs/common';
import { Cache, CACHE_MANAGER, CacheInterceptor } from '@nestjs/cache-manager';
import { MailerService } from '@nestjs-modules/mailer';
import { InjectRedis } from '@nestjs-modules/ioredis';
import Redis from 'ioredis';
//import { PrismaService } from './database/prisma/prisma.service';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from '@/user/user.entity';
import { Repository } from 'typeorm';

@Controller()
@UseInterceptors(CacheInterceptor)
export class AppController {
  constructor(
    @Inject(CACHE_MANAGER) private cacheManager: Cache,
    private readonly mailerService: MailerService,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}

  @Get()
  //@Version('1')
  async getHello(): Promise<any> {
    const res = await this.userRepository.find();
    return res;
  }

  @Get()
  @Version('2')
  async getHello2(@Query('token') token): Promise<any> {
    console.log('传入的 token', token);
    // const res = await this.redis.get('token');
    // await this.redis.set(
    //   'token',
    //   (token as string) || 'default token',
    //   'EX',
    //   60 * 10,
    // );
    const res = await this.cacheManager.get('token');
    await this.cacheManager.set('token', (token as string) || 'default token');
    return {
      token: res,
    };
  }

  @Get('mail')
  async sendMail(): Promise<any> {
    return this.mailerService
      .sendMail({
        to: 'jon.ju@163.com',
        from: '35546560@qq.com',
        subject: 'Testing Nest MailerModule ✔',
        template: './welcome',
        context: {
          name: 'jon.ju',
        },
      })
      .then(() => {
        console.log('mail success');
      })
      .catch((err) => {
        console.log('mail error: ', err);
      });
  }
}
